package com.fare.taluo.core.domain.crawl.adapter.sub;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.NavigableSet;
import java.util.TreeSet;
import java.util.zip.GZIPInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.fare.taluo.core.domain.crawl.CrawlTaskModel;
import com.fare.taluo.core.domain.crawl.PageErrorResultException;
import com.fare.taluo.core.domain.crawl.adapter.AbstractAdapter;
import com.fare.taluo.core.domain.crawl.adapter.CrawlAdapterFactory;
import com.fare.taluo.util.RegHtmlUtil;

/**
 * 南航适配器
 * <p>先将CSAirImpl中的代码搬过来，再来做优化
 *
 */
public class CSAirAdaptor extends AbstractAdapter {

	public CSAirAdaptor(CrawlTaskModel taskModel) {
		super(taskModel);
	}

	@Override
	//将抓取单程的结果组合成vo
	public List<Object> paraseToVo(Object fetchObject) throws Exception {
		List<Object> list = new ArrayList<Object>();
		
			Document d =(Document)fetchObject;
			
			XPathFactory xpf = XPathFactory.newInstance();
			XPath xpath = xpf.newXPath();
	
			//String dateElement = "/page/FLIGHTS/SEGMENT/DATE";
			//String date = (String) xpath.evaluate(dateElement, d,
			//		XPathConstants.STRING);
	
			String root = "/page/FLIGHTS/SEGMENT/DATEFLIGHT/DIRECTFLIGHT/FLIGHT";
			NodeList nodesFLIGHT = (NodeList) xpath.evaluate(root, d,
					XPathConstants.NODESET);
	
			
			for (int i = 0; i < nodesFLIGHT.getLength(); i++) {
				Node n = nodesFLIGHT.item(i);
	
				String FLIGHTNO = xpath.evaluate("FLIGHTNO", n);
				String DEPTIME = xpath.evaluate("DEPTIME", n);
				String ARRTIME = xpath.evaluate("ARRTIME", n);
	
				NodeList nodes = (NodeList) xpath.evaluate(
						"CABINS/CABIN/ADULTPRICE", n, XPathConstants.NODESET);
	
				NavigableSet<Integer> ns = new TreeSet<Integer>();
				for (int b = 0; b < nodes.getLength(); b++) {
					Node dd = nodes.item(b);
					ns.add(Integer.parseInt(dd.getTextContent().trim()));
				}

				list.add(CrawlAdapterFactory.createPlaneInfo(taskModel, "CZ", "南航", "中国南方航空公司", 
						 DEPTIME.trim(), ARRTIME.trim(), FLIGHTNO,
						(ns.size() == 0 ? "" : String.valueOf(ns.first())), null, 
						(ns.size() == 0 ? "" : String.valueOf(ns.last())), null));
				
				
			}
		
		return list;
	}

	@Override
	//获取抓取链接， 返回链接地址
	public String getUrl() throws Exception {
		return "http://b2c.csair.com/B2C40/detail-"
		+ taskModel.getFromCity() + taskModel.getToCity() + "-" + taskModel.getFlightDate().replace("-", "") + "-1-0-0-0-1-0-0-0-1-0.g2c";
	}

	@Override
	//根据链接返回抓取结果
	public Object fetch(String url) throws Exception {
		HttpClient httpClient = null;
		
		HttpPost httpPost = null;
		HttpResponse httpResponse = null;
		HttpEntity entity = null;
		 InputStream gis = null;
		 ByteArrayOutputStream os = null;
		InputStream is = null;
		DocumentBuilderFactory factory = null;
		DocumentBuilder parser = null;

		Document d = null;
		try{
			 httpClient = this.getHttpClient();
			 httpPost = new HttpPost(getUrl());
			
			httpPost.setHeader("x-requested-with", "XMLHttpRequest");
			httpPost.setHeader("Accept-Language", "zh-cn");
			httpPost.setHeader("Referer",
						"http://b2c.csair.com/B2C40/modules/booking/basic/flightSelectDirect.jsp");
			httpPost.setHeader("Accept", "application/xml, text/xml, */*; q=0.01");
			httpPost.setHeader("Accept-Encoding", "gzip, deflate");
			httpPost.setHeader("Host", "b2c.csair.com");
			 httpResponse = httpClient.execute(httpPost);
			 entity = httpResponse.getEntity();
				if (entity != null) {
					is = entity.getContent();
					Header encoding = entity.getContentEncoding();
					if (encoding != null && encoding.getValue().equals("gzip")) {
						 gis = new GZIPInputStream(is);
						 os = new ByteArrayOutputStream();
						int count;
						byte data[] = new byte[1024];
						while ((count = gis.read(data)) > 0) {
							os.write(data, 0, count);
						}
					}
				}
			factory = DocumentBuilderFactory.newInstance();
			parser = factory.newDocumentBuilder();
			d = parser.parse(new ByteArrayInputStream(os.toByteArray()));
			return d;
		}finally{
			 httpPost = null;
			 httpResponse = null;
			 entity = null;
			 if(os != null) 
				 try{os.close();}catch(Exception e){}
			 if(gis != null) 
				 try{gis.close();}catch(Exception e){}
			  gis = null;
			  os = null;
				 factory = null;
				 parser = null;
		}
		
	}

	@Override
	/**
	 * 验证抓取结果是否成功
	 * 1.判断抓取的数据是否为空
	 * 2.判断该航班是否无航班信息
	 * 3.判断数据结构是否是你想要的数据
	 */
	public boolean validateFetch(Object fetchObject) throws Exception {
		if(fetchObject == null){
			return false;
		}else if(fetchObject instanceof String){
			//验证字符串里是否包含抓取的错误信息
			String result = RegHtmlUtil.regStr((String)fetchObject, this.getErrors());
			if(result != null){
				throw new PageErrorResultException(result);
			}
		}
		return true;
	}	
	
	private List<String> getErrors(){
		List<String> airChinaErrors = new ArrayList<String>();
		airChinaErrors.add("404 Not Found");
		airChinaErrors.add("<MESSAGE>NoRoutingException:");
		return airChinaErrors;
	}
	
//	public static void  main(String[] arg) throws Exception{
//		CrawlContext.getInstance().setDebug(true);
//		taskModelRecordEntity taskModel = new taskModelRecordEntity();
//		taskModel.setGrabChannelId(CSAir_GradChannel);
//		taskModel.setGrabChannel("中国南方航空公司官网");
//	//	taskModel.setIsReturn(0);
//		taskModel.setFromCity("CAN");
//		taskModel.setFromCityName("广州");
//		taskModel.setToCity("PEK");
//		taskModel.setToCityName("北京");
//		taskModel.setFlightDate("2013-04-19");
//
//
//		//logger.info("抓取引警系统配置文件统一注册......");
//		ConfigLoader.initLoader();
//		System.out.println("fetch......");
//		CSAirAdaptor c = new CSAirAdaptor(taskModel);
//		
//		Object obj = c.fetch(null);
//		
//		System.out.println(obj.toString());
//		System.out.println("paraseToVo......");
//		List<Object> results = c.paraseToVo(obj);
//		System.out.println("println......");
//		for (Object o : results) {
//			PlaneInfoEntity p = (PlaneInfoEntity)o;
//			System.out.println(p.toString());
//		}
//	}
//	
	public static void main(String[] args) {
		String s = "20130531";
		System.out.println(s.substring(6, 8));
	}
}
